<script lang="ts" setup>
import PageDialog from "@/components/PageDialog/index.vue";
import {ref, watch} from "vue";
import {
  OperatorRentContractObj,
  OperatorRentOrderObj,
  OwnerEleContractObj,
  OwnerRentContractObj
} from "@/api/demoClass";
import {
  addOperatorRent, addOperatorRentOrder,
  addOwnerEle, addOwnerRent, autoCreateRentOrder2, operatorList,
  ownerList,
  ownerPaymentList,
  projectList, stationList
} from "@/api/demoApi";
import {message} from "@/utils/message";
import {timeThan} from "@/utils/timeFormat";

defineOptions({
  name: "registRentDialog"
});

/**-------------------表单相关-------------------**/
//表单参数
const formData = ref({
  id: null,
  stationId:null,
  operatorId:null,
  rentStart:null,
  rentEnd:null,
  rentCycle:null,
  rentOnce: null,
  rentTotal:null,
  rentSigningUnit:null,
  rentInvoiceType:0,
  rentTax: '13%',
  rentInvoiceContent:null,
  remark:null,
  status: 0
})

//表单校验
const formRules = ref({
  stationId:[{required:true,message:'请选择站点',trigger:['blur','change']}],
  operatorId:[{required:true,message:'请选择运营商',trigger:['blur','change']}],
  rentStart:[
    {required:true,message:'请选择合同开始日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.rentEnd) {
          timeThan(formData.value.rentEnd,value) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  rentEnd:[
    {required:true,message:'请选择合同结束日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.rentStart) {
          timeThan(value,formData.value.rentStart) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  rentCycle:[{required:true,message:'请选择场租结算周期',trigger:['blur','change']}],
  rentOnce:[{required:true,message:'请输入租金年金额',trigger:['blur','change']}],
  rentTotal:[{required:true,message:'请输入租金总额',trigger:['blur','change']}],
  rentSigningUnit:[{required:true,message:'请选择开票单位',trigger:['blur','change']}],
  rentInvoiceType:[{required:true,message:'请选择票据类型',trigger:['blur','change']}],
  rentTax:[{required:true,message:'请选择场租税率',trigger:['blur','change']}],
})

//项目选项
const stationOptions = ref([])
const operatorOptions = ref([])
const cycleOptions = [
  {value:0,label:'一年一付',divisor:1},
  {value:1,label:'两年一付',divisor:2},
  {value:2,label:'三年一付',divisor:3},
  {value:3,label:'五年一付',divisor:5},
  {value:4,label:'十年一付',divisor:10},
  {value:5,label:'一次付清',divisor:100},
]
const signingUnitOptions = [
  {label:'晨邦',value: 0},
  {label:'网基',value: 1},
  {label:'优居',value: 2},
  {label:'坤澜',value: 3},
  {label:'晓鹰',value: 4}
]
const invoiceTypeOptions = [
  {label:'专票',value: 0},
  {label:'普票',value: 1}
]
const contentOptions = [
  {label:'信息技术服务费',value:0},
  {label:'塔类站址服务费',value:1},
  {label:'管理费',value:2},
  {label:'租赁费',value:3},
  {label:'综合服务费',value:4},
]
const taxOptions = [
  {label:'1%',value: '1%'},
  {label:'3%',value: '3%'},
  {label:'5%',value: '5%'},
  {label:'6%',value: '6%'},
  {label:'7%',value: '7%'},
  {label:'9%',value: '9%'},
  {label:'11%',value: '11%'},
  {label:'13%',value: '13%'}
]
const getStationOptions = ()=>{
  stationOptions.value = stationList().map(item=>({value:item.id,label:`${item.stationNo}(${item.planName})`}))
}
const getOperatorOptions = ()=>{
  operatorOptions.value = operatorList().map(item=>({value:item.id,label:item.operator}))
}

/**-------------------打开弹框-------------------**/
//标题
const dialogTitle = ref('')
const active = ref(0)
const dialog = ref()
const orderResultData = ref([])
//弹框显示
const dialogShow = (title: string,data?: object)=>{
  dialogTitle.value = title
  if(data) {
    if(title ==='查看') {
      formData.value = {...data}
    }else {
      formData.value.stationId = data.stationId
      formData.value.operatorId = data.operatorId
    }
  }
  getStationOptions()
  getOperatorOptions()
  dialog.value.dialogVisible = true
}
defineExpose({
  dialogShow
})

/**-------------------事件回调-------------------**/
//取消
const form = ref()
const handlerCancel = ()=> new Promise(async (resolve,reject)=>{
  try{
    form.value && await form.value.resetFields()
    active.value = 0
    formData.value = {
      id: null,
      stationId:null,
      operatorId:null,
      rentStart:null,
      rentEnd:null,
      rentCycle:null,
      rentOnce: null,
      rentTotal:null,
      rentSigningUnit:null,
      rentInvoiceType:0,
      rentTax: '13%',
      rentInvoiceContent:null,
      remark:null,
      status: 0
    }
    dialog.value.dialogVisible = false
    resolve({})
  }catch(e){
    console.log(e)
    reject(e)
  }
})
//上一步
const prevHandler = ()=>{
  active.value = 0
}
//下一步
const nextHandler = ()=>{
  active.value = 1
  orderResultData.value = autoCreateRentOrder2(formData.value)
}
//移除某条订单
const removeResultOrder = index => {
  orderResultData.value.splice(index,1)
}
//确认
const emits = defineEmits(['done'])
const handlerConfirm = ()=> new Promise(async (resolve,reject)=>{
  try{
    form.value && await form.value.validate()
    //todo 新增、编辑接口
    const newOwnerEle = new OperatorRentContractObj(formData.value)
    const result = addOperatorRent(newOwnerEle)
    if(!result) {
      orderResultData.value.forEach((item,index)=>{
        const order = new OperatorRentOrderObj(item)
        order.orderNo = `${index}/${orderResultData.value.length}`
        order.contractId = newOwnerEle.id
        addOperatorRentOrder(order)
      })
      message("添加成功", { type: "success" });
      await handlerCancel()
      emits('done')
      resolve({})
    }else {
      message(result, { type: "warning" });
      resolve({})
    }
  }catch(e){
    reject(e)
  }
})
</script>

<template>
  <PageDialog ref="dialog" :buttons="dialogTitle === '查看' ? ['cancel'] : active === 0 ? ['cancel'] : ['confirm']" :handler-cancel="handlerCancel" :handler-confirm="handlerConfirm" :title="dialogTitle">
    <el-form v-if="active === 0" ref="form" :disabled="dialogTitle === '查看'" :model="formData" :rules="formRules" label-position="top" label-width="auto">
      <el-form-item label="站点" prop="stationId">
        <el-select v-model="formData.stationId" clearable disabled filterable placeholder="请选择站点">
          <el-option v-for="(item,index) in stationOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="运营商" prop="operatorId">
        <el-select v-model="formData.operatorId" clearable disabled filterable placeholder="请选择运营商">
          <el-option v-for="(item,index) in operatorOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="rentStart">
        <el-date-picker
          v-model="formData.rentStart"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合同开始日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="rentEnd">
        <el-date-picker
          v-model="formData.rentEnd"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合同开始日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结算周期" prop="rentCycle">
        <el-select v-model="formData.rentCycle" clearable filterable placeholder="请选择场租结算周期">
          <el-option v-for="(item,index) in cycleOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="租金年金额(元)" prop="rentOnce">
        <el-input-number v-model.number="formData.rentOnce" :controls="false" :precision="2" :step="0.01" placeholder="请输入租金年金额(元)"/>
      </el-form-item>
      <el-form-item label="租金年总额(元)" prop="rentTotal">
        <el-input-number v-model.number="formData.rentTotal" :controls="false" :precision="2" :step="0.01" placeholder="请输入租金年总额(元)"/>
      </el-form-item>
      <el-form-item label="开票单位" prop="rentSigningUnit">
        <el-select v-model="formData.rentSigningUnit" clearable filterable placeholder="请选择场租开票单位">
          <el-option v-for="(item,index) in signingUnitOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="票据类型" prop="rentInvoiceType">
        <el-select v-model="formData.rentInvoiceType" clearable filterable placeholder="请选择场租票据类型">
          <el-option v-for="(item,index) in invoiceTypeOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="场租税率" prop="rentTax">
        <el-select v-model="formData.rentTax" clearable filterable placeholder="请选择场租税率">
          <el-option v-for="(item,index) in taxOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开票内容" prop="rentInvoiceContent">
        <el-select v-model="formData.rentInvoiceContent" clearable filterable placeholder="请选择默认开票内容">
          <el-option v-for="(item,index) in contentOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="company">
        <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <!--订单-->
    <template v-if="active===1">
      <el-row class="result_tip" justify="center" type="flex">请确认订单自动生成结果</el-row>
      <el-table :data="orderResultData">
        <el-table-column align="center" type="index" />
        <el-table-column align="center" label="期数" show-overflow-tooltip>
          <template #default="{$index}">
            {{$index + 1}}/{{orderResultData.length}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="开始日期" prop="orderStart" show-overflow-tooltip />
        <el-table-column align="center" label="结束日期" prop="orderEnd" show-overflow-tooltip />
        <el-table-column align="center" label="订单金额(元)" prop="orderPrice" show-overflow-tooltip />
        <el-table-column align="center" label="订单备注" prop="remark" show-overflow-tooltip />
        <el-table-column align="center" label="操作">
          <template #default="{$index}">
            <el-button size="small" text type="danger" @click="removeResultOrder($index)">删除该条</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--    操作-->
    <template #button>
      <el-button v-if="active===1" type="info" @click="prevHandler">
        上一步
      </el-button>
      <el-button v-if="active===0" type="primary" @click="nextHandler">
        下一步
      </el-button>
    </template>
  </PageDialog>
</template>

<style lang="scss" scoped>
:deep(.el-form) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;

  .el-form-item {
    width: 48%;

    .el-input,
    .el-input-number,
    .el-date-picker,
    .el-select {
      width: 100%;
    }
  }
}

.result_tip {
  font-size: 1.5vh;
  color: #999;
  margin-bottom: 1vh;
}
</style>
